<?php
define('MAXITEM', 5);
	
class IndexController extends Zend_Controller_Action
{
	// Fileds
	
	public $page;
	public $sort ;
	public $mincount;
	public $itemcount;
	public $fromDate;
	public $toDate;
	
	
	// Actions
	
    public function indexAction()
    {
    	
        $m = new Application_Model_DbTable_ApiLog();
        $this->getParms();
        $rows = $m->cau1($this->page, $this->sort, $this->mincount, $this->fromDate, $this->toDate, $itemcount);
        $this->itemcount = $itemcount;        
        $this->show($rows);
    }
    
    public function cau2Action() {
    	
        $m = new Application_Model_DbTable_ApiLog();
        
        $this->getParms();
        $dates = $m->getDates($this->fromDate, $this->toDate);
        $this->view->dates = $dates;
        $itemcount = 0;
       	$rows = $m->cau2($this->page, $this->sort, $this->mincount, $this->fromDate, $this->toDate, $itemcount);
       	
        $this->itemcount = $itemcount; 
        $this->show($rows);
    }
    
         
    
    
    
    // Helpers
    
    public function getParms() {
    	$this->page = $this->_getParam("page");
    	$this->sort = $this->_getParam('sort', '');
    	$this->mincount = $this->_getParam("num");
    	$this->fromDate = $this->_getParam("from");
    	$this->toDate = $this->_getParam("to");
    	
    	if ($this->fromDate != '') {
    		setcookie('fromDate', $this->fromDate);
    	} else {
    		$this->fromDate = isset($_COOKIE['fromDate'] ) ? $_COOKIE['fromDate'] : 0 ;
    	}
    	
    	if ($this->toDate != '') {
    		setcookie('toDate', $this->toDate);
    	} else {
    		$this->toDate = isset($_COOKIE['toDate'] ) ?  $_COOKIE['toDate'] : 0 ;
    	}
    	
    	if ($this->page == null) {
    		$this->page = 1;
    	}
    	if ($this->mincount != null) {
    		$this->page = 1;
    		setcookie('mincount', $this->mincount);
    	} else {
    		$this->mincount = isset($_COOKIE['mincount'] ) ? (int)  $_COOKIE['mincount'] : 0 ;
    	}
    	$this->itemcount = 0;
    }
    
    
    public function show($rows) {
    	$this->view->page = $this->page;
    	$maxTotalPage = (int)($this->itemcount/ MAXITEM );
    	if ($this->itemcount % MAXITEM != 0) $this->itemcount++;
    	$this->view->total =  $this->itemcount;
    
    
    	$begin = (int)( $this->page / MAXITEM ) * MAXITEM + ($this->page % MAXITEM == 0 ? - MAXITEM : 0) + 1;
    
    	$next = $begin + MAXITEM;
    
    	$end = $next >= $maxTotalPage ? $maxTotalPage : $next - 1;
    
    	$this->view->fromDate = $this->fromDate;
    	$this->view->toDate = $this->toDate;
    	$this->view->end = $end;
    	$this->view->begin = $begin;
    	$this->view->apis = $rows;
    	$this->view->sort = $this->sort;
    }
    
    
}

